package cn.iocoder.yudao.module.policy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.policy.entity.BannerDO;
import cn.iocoder.yudao.module.policy.mapper.BannerMapper;
import cn.iocoder.yudao.module.policy.service.BannerService;
import cn.iocoder.yudao.module.policy.vo.banner.BannerPageReqVO;
import cn.iocoder.yudao.module.policy.vo.banner.BannerRespVO;
import cn.iocoder.yudao.module.policy.vo.banner.BannerSaveReqVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 轮播图 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class BannerServiceImpl implements BannerService {

    private static final ErrorCode BANNER_NOT_EXISTS = new ErrorCode(0, "未找到数据");
    @Resource
    private BannerMapper bannerMapper;

    @Override
    public Long createBanner(BannerSaveReqVO createReqVO) {
        // 插入
        BannerDO banner = BeanUtils.toBean(createReqVO, BannerDO.class);
        bannerMapper.insert(banner);
        // 返回
        return banner.getId();
    }

    @Override
    public void updateBanner(BannerSaveReqVO updateReqVO) {
        // 校验存在
        validateBannerExists(updateReqVO.getId());
        // 更新
        BannerDO updateObj = BeanUtils.toBean(updateReqVO, BannerDO.class);
        bannerMapper.updateById(updateObj);
    }

    @Override
    public void deleteBanner(Long id) {
        // 校验存在
        validateBannerExists(id);
        // 删除
        bannerMapper.deleteById(id);
    }

    private void validateBannerExists(Long id) {
        if (bannerMapper.selectById(id) == null) {
            throw exception(BANNER_NOT_EXISTS);
        }
    }

    @Override
    public BannerDO getBanner(Long id) {
        return bannerMapper.selectById(id);
    }

    @Override
    public PageResult<BannerDO> getBannerPage(BannerPageReqVO pageReqVO) {
        return bannerMapper.selectPage(pageReqVO);
    }

    @Override
    public List<BannerDO> getBannerList(BannerRespVO pageReqVO) {
        BannerDO bean = BeanUtils.toBean(pageReqVO, BannerDO.class);
        return bannerMapper.selectList(new LambdaQueryWrapper<BannerDO>(bean));
    }

}